// 
//  Author:
//    Anton Lauridsen anton at lauridsen decimal-separator info
// 
//  Copyright (c) 2009, Anton Lauridsen
// 
//  All rights reserved.
// 
//  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// 
//     * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in
//       the documentation and/or other materials provided with the distribution.
//     * Neither the name of the [ORGANIZATION] nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// 
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
//  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// 

using System;
using System.Collections.Generic;
using OpenMetaverse;

namespace OpenFuse.Backend.Commands.Downloaders
{
	public class Downloader
	{
		public static Cache.Asset Download(SlSession session, UUID taskFolderID, UUID parentFolderID, InventoryItem item)
		{
			Cache.Asset result = new Cache.Asset();

			try
			{
				result.AssetId = item.AssetUUID.Guid;
				result.AssetType = item.AssetType;
				result.NodeId = item.UUID.Guid;
				result.OwnerId = item.OwnerID.Guid;
				result.TaskId = Guid.Empty;

				switch(item.AssetType)
				{
					case AssetType.Object:
						result.Data = new Downloaders.ObjectDownloader().Download(session, parentFolderID, item);
						// SL Likes to report a Zero assetUUID, the assetUUID of the item may have been modified
						result.AssetId = item.AssetUUID.Guid;
						break;
					case AssetType.Gesture:
					case AssetType.Landmark:
						break;
					case AssetType.Texture:
					case AssetType.TextureTGA:
					case AssetType.ImageJPEG:
					case AssetType.ImageTGA:
						result.Data = Utilities.DownloadTexture(session, item.AssetUUID);
						break;
					case AssetType.Notecard:
					case AssetType.LSLText:
					case AssetType.LSLBytecode:
						// SL likes to report a Zero UUID on no copy items
						if(item.AssetUUID == UUID.Zero) {
							session.Logger.Debug("Fixed up missing AssetUUID");
							item.AssetUUID = UUID.Random();
							result.AssetId = item.AssetUUID.Guid;
						}
						result.Data = Utilities.DownloadAssetFromInventory(session, taskFolderID, item.UUID, item.AssetUUID, item.AssetType);
						break;
					case AssetType.Bodypart:
					case AssetType.Clothing:
						List<Cache.Asset> subAssets;
						result.Data = new Downloaders.WearableDownloader().Download(session, item, out subAssets);
						result.SubAssets = subAssets;
						break;
					case AssetType.Animation:
						if((item.Permissions.OwnerMask & PermissionMask.Transfer) == 0)
							result.Data = Utilities.DownloadNoTransferAnimation(session, item.AssetUUID);
						else
							goto default;
						break;
					case AssetType.CallingCard:
						session.Logger.Warn("Attempting to download unsupported asset type");
						break;
					default:
						result.Data = new Downloaders.GenericDownloader().Download(session, item);
						break;
				}
				
				if(result.Data == null)
					result.Size = 0;
				else
					result.Size = result.Data.Length;
				
			} catch(Exception ex) {
				session.Logger.ErrorFormat("Error downloading node:\n{0}", ex.ToString());
			}
			if(result.Data == null)
			{
				if(item.AssetType == AssetType.Landmark)
					session.Logger.WarnFormat("Warning landmarks are not supported:'{0}'", item.Name);
				else
					session.Logger.ErrorFormat("Error downloading node:'{0}', {1}", item.Name, item.AssetUUID);
			}

			return result;
		}
		
		public static Cache.Asset Download(SlSession session, Guid parentFolderId, Guid itemId)
		{
			InventoryBase baseItem = session.GridClient.Inventory.Store[new UUID(itemId)];
			session.Logger.DebugFormat("Downloader is looking for: {0} in the store and found '{1}'", itemId, baseItem == null?"nothing":baseItem.Name);
			
			InventoryItem item = baseItem as InventoryItem;
			if(item == null)
			{
				session.Logger.ErrorFormat("'{0}' is not an Item, and cannot be downloaded", baseItem.Name);
				return null;
			}
			
			if(item.AssetType == AssetType.LSLText && (item.Permissions.OwnerMask & PermissionMask.Modify) == 0)
			{
				session.Logger.InfoFormat("Ignoring protected script '{0}'", item.Name);
				return null;
			}
			
			return Download(session, UUID.Zero, new UUID(parentFolderId), (InventoryItem)baseItem);
		}
	}
}
